package de.schoar.nagroid.nagios;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import de.schoar.nagroid.DM;


public class NagiosSite {

	private String mUrlBase;
	private String mUrlUser = null;
	private String mUrlPass = null;
	private boolean mUnhandledOnly = false;

	private LinkedList<NagiosHost> mHosts = new LinkedList<NagiosHost>();

	public NagiosSite(String urlbase, boolean unhandledOnly) {
		this(urlbase, null, null, unhandledOnly);
	}

	public NagiosSite(String urlbase, String urluser, String urlpass,
			boolean unhandledOnly) {
		mUrlUser = urluser;
		mUrlPass = urlpass;
		mUrlBase = urlbase;
		mUnhandledOnly = unhandledOnly;
	}

	public NagiosHost findHost(String name) {
		for (NagiosHost nh : mHosts) {
			if (nh.getName().equals(name)) {
				return nh;
			}
		}
		return null;
	}

	public void addHostFirst(NagiosHost nh) {
		mHosts.addFirst(nh);
	}
	
	public void addHostLast(NagiosHost nh) {
		mHosts.addLast(nh);
	}
	
	public void addHost(NagiosHost nh) {
		mHosts.add(nh);
	}

	public LinkedList<NagiosHost> getHosts() {
		if(DM.I.getConfiguration().getSortType()==1) Collections.sort(mHosts, new NagiosHostComparator());
		return mHosts;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("URL: " + mUrlBase + "\n");
		for (NagiosHost nh : mHosts) {
			sb.append(nh.toString() + "\n");
		}
		return sb.toString();
	}

	public String getUrlBase() {
		return mUrlBase;
	}

	public String getUrlUser() {
		return mUrlUser;
	}

	public String getUrlPass() {
		return mUrlPass;
	}

	public boolean getUnhandledOnly() {
		return mUnhandledOnly;
	}
	
	/* regroup all services corresponds to a same host */
	public void regroup(){
		NagiosHost nh;
		LinkedList <NagiosHost> list = new LinkedList<NagiosHost>();
		Iterator <NagiosHost> it = getHosts().iterator();
		while(it.hasNext()){
			nh = (NagiosHost)it.next();
			if(nh.getAck()==false){
				if(!exist_host(list,nh)){
					if(nh.getState() == NagiosState.HOST_DOWN){
						nh.findPing();
						list.addFirst(nh);
					}
					else list.addLast(nh);	
				}
			}
		}
		mHosts = list;		
	}
	
	/* return true and add services if two hosts are equals */
	public boolean exist_host(LinkedList <NagiosHost> l,NagiosHost nh){
		Iterator <NagiosHost> it = l.iterator();
		while(it.hasNext()){
			NagiosHost ngh = (NagiosHost)it.next();
			if(ngh.getName().equalsIgnoreCase(nh.getName())) {
				if(ngh.getState()==NagiosState.HOST_UP) ngh.getServices().addAll(nh.getServices());
				return true;
			}
		}
		return false;
	}

}

